package com.tdcy.framework;

import java.util.HashMap;
import java.util.Map;

import com.tdcy.framework.exception.BaseException;
import com.tdcy.framework.util.StringUtils;

/**
 * 业务Context.
 */
public abstract class BusiContext {

	/** The thread context. */
	private static ThreadLocal<Map<Object, Object>> threadContext = new ThreadLocal<Map<Object, Object>>();

	/**
	 * 获取所有对象.
	 * 
	 * @return the all context
	 */
	public static Map<Object, Object> getAllContext() {
		return threadContext.get();
	}

	/**
	 * 设置对象.
	 * 
	 * @param key
	 *            对象名称
	 * @param value
	 *            对象值
	 */
	public static void setContext(final Object key, final Object value) {
		if (StringUtils.isEmptyString(key)) {
			return;
		}

		Map<Object, Object> context = getAllContext();
		if (context == null) {
			context = new HashMap<Object, Object>();
			threadContext.set(context);
		}
		context.put(key, value);
	}

	/**
	 * 设置对象.
	 * 
	 * @param context
	 *            添加
	 */
	public static void setContext(final Map<Object, Object> context) {
		if (StringUtils.isEmpty(context)) {
			return;
		}

		Map<Object, Object> all = getAllContext();
		if (all == null) {
			all = new HashMap<Object, Object>();
			threadContext.set(all);
		}

		all.putAll(context);
	}

	/**
	 * 删除对象.
	 * 
	 * @param key
	 *            对象名称
	 * 
	 * @return 与指定对象名称关联的值，如果不存在返回null
	 */
	public static Object removeContext(final Object key) {
		Map<Object, Object> context = getAllContext();
		if (context == null) {
			return null;
		}

		return context.remove(key);
	}

	/**
	 * 获取对象.
	 * 
	 * @param key
	 *            对象名称(不存在将抛查找错误的异常）
	 * 
	 * @return 对象值
	 * 
	 * @throws BaseException
	 *             the exception
	 */
	public static Object getContext(final Object key) throws BaseException {
		Map<Object, Object> context = getAllContext();

		if (context != null && context.containsKey(key)) {
			return context.get(key);
		} else {
			return null;
		}
	}

	/**
	 * 获取对象.
	 * 
	 * @param key
	 *            对象名称
	 * @param defaultValue
	 *            缺省值
	 * 
	 * @return 对象值
	 */
	public static Object getContext(final Object key, final Object defaultValue) {
		Map<Object, Object> context = getAllContext();
		if (context != null) {
			Object val = context.get(key);
			return (val == null) ? defaultValue : val;
		} else {
			return defaultValue;
		}
	}

	/**
	 * 清理业务环境对象.
	 */
	public static void cleanup() {
		try {
			threadContext.set(null);
			threadContext.remove();

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
